﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic;

namespace AricentTestProject
{
    public partial class Search : BasePage
    {
        private List<UserInfo> _friends;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (CurrentUser == null)
                Response.Redirect("/");

            string q = Request.QueryString["q"];
            if (!string.IsNullOrEmpty(q) && q.Length > 2)
            {
                _friends = CurrentUser.getFriends();

                var found = q.findUsers();
                FoundUsers.DataSource = found;
                FoundUsers.DataBind();                
            }
        }

        protected void FoundUsers_OnItemCreated(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var addLB = e.Item.FindControl("AddToFriendLB") as LinkButton;
                if (_friends.Find(i => i.Id == ((UserInfo)e.Item.DataItem).Id) == null)
                {
                    addLB.Click += new EventHandler(addLB_Click);
                }
                else
                {
                    addLB.Enabled = false;
                }

            }
        }

        void addLB_Click(object sender, EventArgs e)
        {
            var lb = (LinkButton)sender;
            CurrentUser.addFriend(new Guid(lb.CommandArgument));
            lb.Enabled = false;
        }
    }
}
